import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'components/home.dart';
import 'components/login/login.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

void main() {
  runApp(App());
  configLoading();
}

void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.custom
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.blue
    ..backgroundColor = Colors.white
    ..indicatorColor = Colors.blue
    ..textColor = Colors.blue
    ..maskColor = Colors.blue.withOpacity(0)
    ..userInteractions = true
    ..dismissOnTap = false;
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '密码本',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: AppHome(),
      routes: {'/login': (context) => Login(), '/home': (context) => Home()},
      builder: EasyLoading.init(),
    );
  }
}

class AppHome extends StatefulWidget {
  @override
  _AppHomeState createState() => _AppHomeState();
}

class _AppHomeState extends State<AppHome> {
  var loginState;
  void initState() {
    super.initState();
    _validateLogin();
  }

  Future _validateLogin() async {
    Future future = Future(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs.getString("user_token");
    });
    future.then((val) {
      if (val == null) {
        setState(() {
          loginState = 0;
        });
      } else {
        setState(() {
          loginState = 1;
        });
      }
    }).catchError((_) {
      print("catchError");
    });
  }

  @override
  Widget build(BuildContext context) {
    if (loginState != null) {
      return loginState == 0 ? Login() : Home();
    } else {
      return Loading();
    }
  }
}

class Loading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: new BoxDecoration(
          color: Color(0xffFFF1CA),
        ),
        child: Image.asset('images/loading.gif'));
  }
}
